﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors; 
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using System.Linq;
using DAL;
using BLL;
using DTO;
using DevExpress.LookAndFeel;
using DevExpress.XtraGrid.Columns;

namespace CRM.GUI.QLCuocGoi
{
    public partial class frmCall : DevExpress.XtraEditors.XtraForm
    {

        public frmCall(string number)
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            UserLookAndFeel.Default.SetSkinStyle("Office 2007 Blue");
            
            InitializeComponent();
            IntialLoad();
            IntialConfig();
            LoadCus(number);
        }


        //=========================================
        IBDetailEntity _ib = new IBDetailEntity();
        CustomerEntity _customer;
        IBDetailFunc _ibFunc = new IBDetailFunc();

        private void IntialConfig()
        {
            grdviewcallHistory.BestFitColumns();
            grdviewcallHistory.OptionsView.ColumnAutoWidth = false;
            grdviewcallHistory.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            grdviewcallHistory.HorzScrollVisibility = ScrollVisibility.Always;


            grdViewNew.BestFitColumns();
            grdViewNew.OptionsView.ColumnAutoWidth = false;
            grdViewNew.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            grdViewNew.HorzScrollVisibility = ScrollVisibility.Always;

            colRecord.UnboundType = DevExpress.Data.UnboundColumnType.String;
            colCallDuration.UnboundType = DevExpress.Data.UnboundColumnType.String;
            grdViewRecord.CustomUnboundColumnData += colRecord_CustomUnboundColumnData;
            grdViewRecord.CustomUnboundColumnData += colCallDuration_CustomUnboundColumnData; 
        }

       
        private void IntialLoad()
        { 
            cmbBranIDLookUp.DataSource = SharedData.BrandList;
            cmbBranIDLookUp.DisplayMember = "BrandName";
            cmbBranIDLookUp.ValueMember = "Brand_ID";            

            colrepBrandName.DataSource = SharedData.BrandList;
            colrepBrandName.DisplayMember = "BrandName";
            colrepBrandName.ValueMember = "Brand_ID";
            GridColumn qColumn = colrepBrandName.View.Columns.AddField("Brand_Code");
            GridColumn wColumn = colrepBrandName.View.Columns.AddField("BrandName");
            qColumn.Visible = true;
            wColumn.Visible = true;
            qColumn = gridView1.Columns["Brand_Code"];
            qColumn.Caption = "Mã sữa";
            wColumn = gridView1.Columns["BrandName"];
            wColumn.Caption = "Tên sữa";
            

            cmbWard.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 4).ToList();
            cmbWard.DisplayMember = "RegionName";
            cmbWard.ValueMember = "Region_Code";

            cmbDistrict.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 3).ToList();
            cmbDistrict.DisplayMember = "RegionName";
            cmbDistrict.ValueMember = "Region_Code";

            cmbProvince.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 2).ToList();
            cmbProvince.DisplayMember = "RegionName";
            cmbProvince.ValueMember = "Region_Code";

            
        }

        private void InitGrid()
        {
            grdcallNew.ForceInitialize();

            colrepBrandName.DataSource = SharedData.BrandList;
            colrepBrandName.DisplayMember = "Brand_Code";
            colrepBrandName.ValueMember = "Brand_ID";

            GridColumn bColumn = colrepBrandName.View.Columns.AddField("Brand_Code");
            GridColumn cColumn = colrepBrandName.View.Columns.AddField("BrandName");

            bColumn.Visible = true;
            cColumn.Visible = true;

            bColumn = gridView1.Columns["Brand_Code"];
            bColumn.Caption = "Mã sữa";
            cColumn = gridView1.Columns["BrandName"];
            cColumn.Caption = "Tên sữa";

        }
        private DataTable CreateDataTable()
        {
            DataTable _table = new  DataTable();
            _table.Columns.Add("DateOfComplain",typeof (DateTime ));
            _table.Columns.Add("SourceReciving", typeof(string));
            _table.Columns.Add("Customer_ID", typeof(int));
            _table.Columns.Add("NXS", typeof(DateTime));
            _table.Columns.Add("HSD", typeof(DateTime));
            _table.Columns.Add("BrandNameID", typeof(int));
            _table.Columns.Add("ReasonComplain", typeof(string));
            _table.Columns.Add("Status", typeof(string));
            _table.Columns.Add("CRMResponse", typeof(string));
            _table.Columns.Add("SupplyResponse", typeof(string));
            _table.Columns.Add("FactoryResponse", typeof(string));
             _table.Columns.Add("ProductExchange", typeof(string));
            _table.Columns.Add("GiftProduct", typeof(string));
            _table.Columns.Add("DatetoFeedBack", typeof(DateTime));

            return _table;
        }

        private void LoadCus(string phonenumber)
        {
            _customer = _ibFunc.LoadCustomerByPhone(phonenumber);
            if (_customer != null)
            {
                _ib.Customer_ID = _customer.Customer_ID;
                txtFirstName.Text = _customer.FirstName;
                txtLastName.Text = _customer.LastName;
                txtPhone.Text = phonenumber;
                txtStreet.Text = _customer.Street;
                txtSubStreet.Text = _customer.SubStreet;

                if (_customer.Province_Code != null)
                {
                    cmbProvince.SelectedValue = _customer.Province_Code;
                }
                if (_customer.District_Code != null)
                {
                    cmbDistrict.SelectedValue = _customer.District_Code;
                }
                if (_customer.Ward_Code != null)
                {
                    cmbWard.SelectedValue = _customer.Ward_Code;
                }

                var data = _ibFunc.LoadIBDetailByCustomerID(_ib.Customer_ID);
                if (data != null)
                {
                    if (data.Count > 1)
                    {
                        grdcallHistory.DataSource = data[0];
                        grdRecord.DataSource = data[1];
                    }
                    else
                    {
                        grdcallHistory.DataSource = data[0];
                    }
                }
                grdViewRecord.BestFitColumns();
                grdviewcallHistory.BestFitColumns();
                grdViewRecord.MoveLast();
                grdviewcallHistory.MoveLast();
                grdcallNew.DataSource = CreateDataTable();
                grdViewNew_addRow();
                grdcallNew.Refresh();                
            }
            else
            {
                txtPhone.Text = phonenumber;
            }

        }

        private void RefreshRegion()
        {
            ////refresh
            //cmbDistrict.DataSource = null;
            //cmbWard.DataSource = null;
            //if (cmbProvince.SelectedValue != null)
            //{
            //    cmbDistrict.DataSource = SharedData.RegionList.Where(a => a.Parent_Code == (int)cmbProvince.SelectedValue).ToList();
            //}
            //else
            //{
            //    cmbWard.DataSource = null;
            //}
            //if (cmbDistrict.SelectedValue != null)
            //{
            //    cmbWard.DataSource = SharedData.RegionList.Where(a => a.Parent_Code == (int)cmbDistrict.SelectedValue).ToList();
            //}
            //else
            //{
            //    cmbWard.DataSource = null;
            //}
        }

        private void cmbDistrict_SelectionChangeCommitted(object sender, EventArgs e)
        {
            RefreshRegion();
        }

        private void cmbProvince_SelectionChangeCommitted(object sender, EventArgs e)
        {
            RefreshRegion();
        }

        private void cmbDistrict_Click(object sender, EventArgs e)
        {
            RefreshRegion();
        }

        private void cmbWard_Click(object sender, EventArgs e)
        {
            RefreshRegion();
        }

        private void grdViewNew_addRow()
        {         
            grdViewNew.AddNewRow();

            int bottomRow = grdViewNew.RowCount - 1;
            grdViewNew.SetRowCellValue(bottomRow, clnSourceReciving, "");
            grdViewNew.SetRowCellValue(bottomRow, clnNSX, "");
            grdViewNew.SetRowCellValue(bottomRow, clnHSD, "");
            grdViewNew.SetRowCellValue(bottomRow, clnBrandNameID, "");
            grdViewNew.SetRowCellValue(bottomRow, clnReasonComplain, "");
            grdViewNew.SetRowCellValue(bottomRow, clnStatus, "");
            grdViewNew.SetRowCellValue(bottomRow, clnCRMResponse, "");
            grdViewNew.SetRowCellValue(bottomRow, clnSupplyResponse, "");
            grdViewNew.SetRowCellValue(bottomRow, clnFactoryResponse, "");
            grdViewNew.SetRowCellValue(bottomRow, clnProductExchange, "");
            grdViewNew.SetRowCellValue(bottomRow, clnGiftProduct, "");
            grdViewNew.SetRowCellValue(bottomRow, clnDatetoFeedBack, "");
            grdcallNew.Refresh();     
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {

            int i = 0;
            for (i = 0; i < this.grdViewNew.RowCount; i++)
            {
                _ib.DateOfComplain = DateTime.Parse(ServerDateTime.SystemDateTime.ToShortDateString());

                if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(i, clnNSX).ToString()))
                { _ib.NSX = null; }
                else
                { _ib.NSX = DateTime.Parse(grdViewNew.GetRowCellValue(i, clnNSX).ToString()); }


                if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(i, clnHSD).ToString()))
                { _ib.HSD = null; }
                else
                { _ib.HSD = DateTime.Parse(grdViewNew.GetRowCellValue(i, clnHSD).ToString()); }


                if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(i, clnDatetoFeedBack).ToString()))
                { _ib.DatetoFeedBack = null; }
                else
                { _ib.DatetoFeedBack = DateTime.Parse(grdViewNew.GetRowCellValue(i, clnDatetoFeedBack).ToString()); }


                if (string.IsNullOrEmpty(grdViewNew.GetRowCellValue(i, clnBrandNameID).ToString()))
                {
                    MessageBox.Show("Vui lòng nhập Tên sản phẩm", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    _ib.BrandNameID = int.Parse(grdViewNew.GetRowCellValue(i, clnBrandNameID).ToString());
                }


                _ib.SourceReciving = grdViewNew.GetRowCellValue(i, clnSourceReciving).ToString();
                _ib.ReasonComplain = grdViewNew.GetRowCellValue(i, clnReasonComplain).ToString();
                _ib.Status = grdViewNew.GetRowCellValue(i, clnStatus).ToString();
                _ib.CRMResponse = grdViewNew.GetRowCellValue(i, clnCRMResponse).ToString();
                _ib.SupplyResponse = grdViewNew.GetRowCellValue(i, clnSupplyResponse).ToString();
                _ib.FactoryResponse = grdViewNew.GetRowCellValue(i, clnFactoryResponse).ToString();
                _ib.ProductExchange = grdViewNew.GetRowCellValue(i, clnProductExchange).ToString();
                _ib.GiftProduct = grdViewNew.GetRowCellValue(i, clnGiftProduct).ToString();
                _ib.Customer_ID = _customer.Customer_ID;

                _ibFunc.AddIBDetail(_ib);

            }

            for (int j = 0; j < i; j++)
            {
                grdViewNew.DeleteRow(j);
            }

            grdcallNew.Refresh();
            grdcallHistory.Refresh();
            var data = _ibFunc.LoadIBDetailByCustomerID(_ib.Customer_ID);
            if (data != null)
            {
                if (data.Count > 1)
                {
                    grdcallHistory.DataSource = data[0];
                    grdRecord.DataSource = data[1];
                }
                else
                {
                    grdcallHistory.DataSource = data[0];
                }
            }
            grdviewcallHistory.BestFitColumns();
            grdViewRecord.BestFitColumns();
            grdviewcallHistory.MoveLast();
            grdViewRecord.MoveLast();

        }

        private void colRecord_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
            {
                var tmp = (RecordEntity) e.Row;
                if (e.Column.Name == "colRecord")
                {
                    e.Value = "Tải xuống";
                }
            }
        }

        private void colCallDuration_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
            {
                var data = e.Row as RecordEntity;
                if (e.Column.Name == "colCallDuration")
                {
                    e.Value = HelperClass.GetDuration(data.Duration);
                }
            }
        }
        

        private void frmCall_FormClosing(object sender, FormClosingEventArgs e)
        {
            //CallMonitor c = new CallMonitor();
            //c.ReadyToCall();
        }

        private void grdViewRecord_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.Name == "colRecord")
            {
                var data = (RecordEntity)grdViewRecord.GetRow(e.RowHandle);
                if (!string.IsNullOrEmpty(data.RecordLink))
                {
                    CallManagement cm = new CallManagement();
                    cm.DownloadFileRecord(data.RecordLink);
                    MessageBox.Show("Đã download xong!!!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.None);
                }
            }
        }
      
    }
}